<?php

include ROOT.'engine'.DS.'core'.DS.'defines.php';
include CORE.'fn.core.php';
include CORE.'class.db.php';
include CORE.'class.cache.php';
include CORE.'app.controller.php';
include CORE.'app.model.php';
include APP.'app.config.php';

is_update_page($update_ips,$update_page);

include_dir(ENGINE.'fn',true);

$engine = routes($default_controller);

extract($engine);

define('CONTROLLER',$controller);
define('ACTION',$action);
define('FORMAT',$format);

$file_controller = CONTROLLERS.CONTROLLER.'_controller.php';

if(file_exists($file_controller)) {
	
	include APP.'app.controller.php';
	include APP.'app.model.php';
	include $file_controller;
	
	$class_controller = str_replace(chr(32),'',ucwords(str_replace('_', chr(32),CONTROLLER))).'Controller';
	
	if(class_exists($class_controller)) {
		
		$class = new $class_controller();
		
		if(isset($class->models)) {
			foreach($class->models as $model) {
				if(!@include MODELS.strtolower($model).'.php') {
					error_404(4,'Model <strong>'.$model.'</strong> not found');
				}
			}
		} else {
			include_dir(MODELS,true);
		}
		
		@include HELPERS.'engine_helper.php';
		@include LIBS.'engine_lib.php';
		@include HELPERS.CONTROLLER.'_helper.php';
		@include LIBS.CONTROLLER.'_lib.php';
		
		if(method_exists($class, $action.'_'.$format)) {
			$view = $action.'_'.$format;
		} elseif(method_exists($class, $action) && public_actions($action)) {
			$view = $action;
		} elseif(method_exists($class, 'error')) {
			$view = 'error';
		} else {
			error_404(3,'Action <strong>'.ACTION.'</strong> not found');
		}
		
		if(isset($class->before_action)) {
			if(in_array($view, $class->before_action)) $class->before_action();
		} else {
			$class->before_action();
		}

		$views = $class->$view();
		
		if(isset($class->after_action)) {
			if(in_array($view, $class->after_action)) $class->after_action();
		} else {
			$class->after_action();
		}

		if(!isset($content_type)) content_type();
		
		$gov = get_object_vars($class);
		extract($gov);
		
		if(!is_null($views)) {
			if(is_array($views)) {
				foreach($views as $view) {
					include $view;
				}
			} elseif(is_object($views)) {
				//coming soon
			} else {
				echo $views;
			}
		} else {
			include _view($view);
		}
		
	} else {
		error_404(2,'Class Controller <strong>'.CONTROLLER.'</strong> not found');
	}
	
} else {
	error_404(1,'Controller <strong>'.CONTROLLER.'</strong> not found');
}

?>